package com.example.demo2Jdbc;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/edit")
public class EditServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = resp.getWriter();
        int id = Integer.parseInt(req.getParameter("id"));
        //1.加载驱动程序
        try {
            Class.forName("com.mysql.jdbc.Driver");
            // 2.获得数据库连接
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstore?serverTimezone=UTC", "root", "root");
            //3.执行SQL语句，实现增、删、改、查操作
            String sql = "select * from book where Bookid=?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            ResultSet rs = pstmt.executeQuery();
            //如果有数据，rs.next() 返回true
            out.print("<html charset= 'utf-8'><head><title>修改</title><body>");
            out.print("<form action='update' method='post'>");
            while (rs.next()) { //4.结果处理
                out.println("编号: <input type='text' readonly='true' value=" + rs.getInt("Bookid") + " name='id' /><br/>");
                out.println("书名: <input type='text' value='" + rs.getString("Title") + "' name='title'/><br/>");
                out.println("作者: <input type='text' value='" + rs.getString("Author") + "' name='author' /><br/>");
                out.println("价格: <input type='text' value='" + rs.getInt("Price") + "' name='price' /><br/>");
                out.println("<input type='submit' value= '修改' /></form>");
            }
            out.print("</body></html>");
            rs.close();
            pstmt.close();
            conn.close(); //5.关闭连接
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


